package com.mrzhou.web.config;

import com.mrzhou.web.exception.CloudErrorController;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.autoconfigure.condition.SearchStrategy;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.Servlet;

@Configuration
@AutoConfigureBefore(ErrorMvcAutoConfiguration.class) // 当前的配置加载顺序应在ErrorMvcAutoConfiguration.class之前
@ConditionalOnWebApplication // 当spring应用为web应用时, 当前配置才生效
@ConditionalOnClass({Servlet.class, DispatcherServlet.class}) // 当给定的类名在类路径上存在，则实例化当前Bean
public class ErrorMvcConfiguration {

    private final ServerProperties serverProperties;

    public ErrorMvcConfiguration(ServerProperties serverProperties) {
        this.serverProperties = serverProperties;
    }

    @Bean
    @ConditionalOnMissingBean(value = {ErrorController.class}, search = SearchStrategy.CURRENT)
    public CloudErrorController cloudErrorController(ErrorAttributes errorAttributes) {
        return new CloudErrorController(errorAttributes, this.serverProperties.getError());
    }

}
